package com.example.demo.interceptor;

import com.alibaba.fastjson.JSONObject;
import com.example.demo.model.UserModel;
import org.springframework.lang.Nullable;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * Admin使用的拦截器
 */
@Component
public class AdminInterceptor implements HandlerInterceptor {

    @Resource HttpSession httpSession;

    /**
     * 处理请求之前执行
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        Object adminInfo = httpSession.getAttribute("adminInfo");
        // 如果没有登录则去登陆页面
        if(adminInfo == null)
        {
            response.sendRedirect("/back/login");
            return false;
        }
        // true 代表放行
        return true;
    }

    /**
     * 处理请求之后执行
     * @param request
     * @param response
     * @param handler
     * @param modelAndView
     * @throws Exception
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable ModelAndView modelAndView) throws Exception {

    }

    /**
     * 客户端返回响应之后执行
     * @param request
     * @param response
     * @param handler
     * @param ex
     * @throws Exception
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable Exception ex) throws Exception {

    }
}
